<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="user-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入用户名"
              :disabled="isEdit"
              @blur="checkUserName"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入昵称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="!isEdit" :gutter="20">
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              @blur="checkEmail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              v-model="form.phonenumber"
              placeholder="请输入手机号"
              @blur="checkPhone"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="form.sex"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option label="男" value="0" />
              <el-option label="女" value="1" />
              <el-option label="未知" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择状态"
              style="width: 100%"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="form.roleIds"
          placeholder="请选择角色"
          multiple
          style="width: 100%"
          :loading="rolesLoading"
        >
          <el-option
            v-for="role in availableRoles"
            :key="role.id"
            :label="role.roleName"
            :value="role.id"
          >
            <div class="role-option">
              <span class="role-name">{{ role.roleName }}</span>
              <span class="role-description">{{ role.description }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <AvatarUploader
          :user-id="isEdit ? form.userId : undefined"
          :initial-avatar="form.avatar"
          @success="handleAvatarUploadSuccess"
          @delete="handleAvatarDelete"
          @error="handleAvatarUploadError"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import AvatarUploader from "@/components/AvatarUploader/index.vue";
import {
  createUserApi,
  updateUserApi,
  checkUserNameApi,
  checkEmailApi,
  checkPhoneApi,
  getUserId,
  type UserInfo,
  type CreateUserRequest,
  type UpdateUserRequest
} from "@/api/user-management";
import { type FileUploadResult } from "@/api/upload";
import { getAvailableRolesApi, type RoleInfo } from "@/api/role-management";

interface Props {
  visible: boolean;
  formData: UserInfo | null;
  isEdit: boolean;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);
const dialogVisible = ref(false);
const rolesLoading = ref(false);
const availableRoles = ref<RoleInfo[]>([]);

// 表单数据
const form = reactive({
  userId: undefined as number | undefined,
  userName: "",
  nickName: "",
  password: "",
  email: "",
  phonenumber: "",
  sex: "2",
  status: 1,
  avatar: "",
  roleIds: [] as number[]
});

// 表单验证规则
const rules: FormRules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 30,
      message: "用户名长度在 3 到 30 个字符",
      trigger: "blur"
    },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "用户名只能包含字母、数字和下划线",
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

// 监听visible变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val) {
      nextTick(() => {
        resetForm();
        loadAvailableRoles();
        if (props.formData && props.isEdit) {
          Object.assign(form, {
            userId: props.formData.userId,
            userName: props.formData.userName,
            nickName: props.formData.nickName || "",
            email: props.formData.email || "",
            phonenumber: props.formData.phonenumber || "",
            sex: props.formData.sex || "2",
            status: props.formData.status,
            avatar: props.formData.avatar || "",
            roleIds: props.formData.roles?.map(role => role.id) || []
          });
        }
      });
    }
  }
);

// 监听dialogVisible变化
watch(dialogVisible, val => {
  emit("update:visible", val);
});

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    userId: undefined,
    userName: "",
    nickName: "",
    password: "",
    email: "",
    phonenumber: "",
    sex: "2",
    status: 1,
    avatar: "",
    roleIds: []
  });
};

// 加载可用角色
const loadAvailableRoles = async () => {
  rolesLoading.value = true;
  try {
    console.log("开始加载可用角色列表...");
    const result = await getAvailableRolesApi();
    console.log("角色列表API响应:", result);

    if (result.code === 200) {
      availableRoles.value = result.data || [];
      console.log("设置可用角色:", availableRoles.value);
    } else {
      ElMessage.error(result.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("获取角色列表失败，请检查网络连接");
  } finally {
    rolesLoading.value = false;
  }
};

// 检查用户名是否存在
const checkUserName = async () => {
  if (!form.userName || props.isEdit) return;

  try {
    const response = await checkUserNameApi(form.userName);
    if (response.code === 200 && response.data) {
      ElMessage.warning("用户名已存在");
      return false;
    }
    return true;
  } catch (error) {
    console.error("检查用户名失败:", error);
    return true;
  }
};

// 检查邮箱是否存在
const checkEmail = async () => {
  if (!form.email) return;

  try {
    const excludeUserId =
      props.isEdit && props.formData ? props.formData.userId : undefined;
    const response = await checkEmailApi(form.email, excludeUserId);
    if (response.code === 200 && response.data) {
      ElMessage.warning("邮箱已存在");
      return false;
    }
    return true;
  } catch (error) {
    console.error("检查邮箱失败:", error);
    return true;
  }
};

// 检查手机号是否存在
const checkPhone = async () => {
  if (!form.phonenumber) return;

  try {
    const excludeUserId =
      props.isEdit && props.formData ? props.formData.userId : undefined;
    const response = await checkPhoneApi(form.phonenumber, excludeUserId);
    if (response.code === 200 && response.data) {
      ElMessage.warning("手机号已存在");
      return false;
    }
    return true;
  } catch (error) {
    console.error("检查手机号失败:", error);
    return true;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 检查重复性
    if (!props.isEdit) {
      const userNameValid = await checkUserName();
      if (!userNameValid) return;
    }

    if (form.email) {
      const emailValid = await checkEmail();
      if (!emailValid) return;
    }

    if (form.phonenumber) {
      const phoneValid = await checkPhone();
      if (!phoneValid) return;
    }

    loading.value = true;

    if (props.isEdit && props.formData) {
      // 编辑用户
      console.log("=== 编辑用户调试信息 ===");
      console.log("props.formData:", props.formData);
      console.log("props.formData的所有属性:", Object.keys(props.formData));
      console.log("props.formData.userId:", props.formData.userId);
      console.log("props.formData.id:", props.formData.id);

      const userId = getUserId(props.formData);
      console.log("getUserId返回的结果:", userId);

      if (!userId || userId === 0) {
        console.error("❌ 用户ID验证失败，尝试从其他字段获取");
        console.error("formData内容:", JSON.stringify(props.formData, null, 2));

        // 尝试直接从formData中获取可能的ID字段
        let fallbackUserId = 0;
        const idFields = ["userId", "id", "user_id", "ID", "User_ID"];

        for (const field of idFields) {
          const value = props.formData[field];
          if (value && !isNaN(Number(value)) && Number(value) > 0) {
            fallbackUserId = Number(value);
            console.log(`🔄 从字段 ${field} 获取到备用ID: ${fallbackUserId}`);
            break;
          }
        }

        if (fallbackUserId > 0) {
          console.log("✅ 使用备用用户ID:", fallbackUserId);
          // 使用备用ID继续执行
          const updateData: UpdateUserRequest = {
            email: form.email,
            phonenumber: form.phonenumber,
            sex: form.sex,
            status: form.status,
            avatar: form.avatar
          };

          console.log("编辑用户 - updateData:", updateData);
          console.log(
            "调用API:",
            `updateUserApi(${fallbackUserId}, updateData)`
          );

          const response = await updateUserApi(fallbackUserId, updateData);
          console.log("编辑用户 - API响应:", response);

          if (response.code === 200) {
            ElMessage.success("用户更新成功");
            emit("success");
          } else {
            ElMessage.error(response.message || "用户更新失败");
          }
          loading.value = false;
          return;
        } else {
          ElMessage.error("用户ID不能为空，请检查控制台日志");
          loading.value = false;
          return;
        }
      }

      console.log("✅ 用户ID验证通过:", userId);

      const updateData: UpdateUserRequest = {
        nickName: form.nickName,
        email: form.email,
        phonenumber: form.phonenumber,
        sex: form.sex,
        status: form.status,
        avatar: form.avatar,
        roleIds: form.roleIds
      };

      console.log("编辑用户 - updateData:", updateData);
      console.log("调用API:", `updateUserApi(${userId}, updateData)`);

      const response = await updateUserApi(userId, updateData);
      console.log("编辑用户 - API响应:", response);

      if (response.code === 200) {
        ElMessage.success("用户更新成功");
        emit("success");
      } else {
        ElMessage.error(response.message || "用户更新失败");
      }
    } else {
      // 新增用户
      const createData: CreateUserRequest = {
        userName: form.userName,
        nickName: form.nickName,
        password: form.password,
        email: form.email,
        phonenumber: form.phonenumber,
        sex: form.sex,
        status: form.status,
        avatar: form.avatar,
        roleIds: form.roleIds
      };

      const response = await createUserApi(createData);
      if (response.code === 200) {
        ElMessage.success("用户创建成功");
        emit("success");
      } else {
        ElMessage.error(response.message || "用户创建失败");
      }
    }
  } catch (error) {
    console.error("表单提交失败:", error);
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

// 头像上传成功处理
const handleAvatarUploadSuccess = (result: FileUploadResult) => {
  console.log("头像上传成功:", result);
  form.avatar = result.fileUrl;
  ElMessage.success("头像上传成功");
};

// 头像删除处理
const handleAvatarDelete = () => {
  console.log("头像删除成功");
  form.avatar = "";
  ElMessage.success("头像删除成功");
};

// 头像上传错误处理
const handleAvatarUploadError = (error: any) => {
  console.error("头像上传失败:", error);
  ElMessage.error("头像上传失败，请重试");
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.user-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  text-align: right;
}

.role-option {
  display: flex;
  flex-direction: column;

  .role-name {
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .role-description {
    margin-top: 2px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}
</style>
